package team.first.mongodb;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import team.first.mongodb.doc.GenreDoc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MorphiaGenreImport {
    public static final String MONGO_DB_NAME = "movie_db";
    public static final String MONGO_DB_USERNAME = "user";
    public static final String MONGO_DB_PASSWORD = "123456";

    public static void main(String[] args) {
        // Mongo数据库地址
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);

        // Mongo数据库的认证信息
        MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_DB_USERNAME, MONGO_DB_NAME,
                MONGO_DB_PASSWORD.toCharArray());
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyToClusterSettings(builder ->
                        builder.hosts(Arrays.asList(serverAddress)))
                .credential(mongoCredential).build();

        // MongoClient必须是com.mongodb.client.MongoClient
        MongoClient mongoClient = MongoClients.create(mongoClientSettings);

        // 下面是使用Mongo java driver 原生插入文档的写法
        /*
        MongoDatabase movieDb = mongoClient.getDatabase(DB_NAME);
        MongoCollection<Document> genreCollection = movieDb.getCollection("genre");
        Document doc = new Document("id", 1).append("name", "剧情");
        genreCollection.insertOne(doc);
        */

        // 下面是使用Morphia的写法 Morphia要求Java 11+版本
        // GenreDoc genre = new GenreDoc().setId(1).setName("剧情");

        Datastore datastore = Morphia.createDatastore(mongoClient, MONGO_DB_NAME);

       /* 自动扫描包下的实体类
        datastore.getMapper().mapPackage("cn.edu.nxu.it");*/

        // 显式指定要映射的实体类
        datastore.getMapper().map(GenreDoc.class);

        // 插入单条数据，如果集合不存在，会自动创建
        // datastore.save(genre);

        // 从数据库查出来值，批量插入
        String sqlGetALLGenres = "SELECT id, name FROM genre ORDER BY id";
        try {
            List<Entity> entityList = Db.use().query(sqlGetALLGenres);
            List<GenreDoc> genreDocList = new ArrayList<>();

            entityList.forEach(entity -> {
                GenreDoc genre1 = new GenreDoc();
                genre1.setId(entity.getInt("id"));
                genre1.setName(entity.getStr("name"));
                // 单个插入，效率低
                // datastore.save(genre1);
                genreDocList.add(genre1);
            });
            datastore.save(genreDocList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
